﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Chapter21.Models.SynchronizationSamples
{
    using System.Threading;

    public static class Demo
    {
        public static void InvokeAll()
        {
            Action line = () =>
            {
                Console.ReadLine();
            };
            Invoke(ThreadJob, line, ThreadMonitor, line);
        }
        public static void Invoke(params Action[] actions)
        {
            foreach (var action in actions)
            {
                action();
            }
        }
        public static void ThreadJob()
        {
            int numTasks = 20;
            var state = new SharedState();
            var tasks = new Task[numTasks];
            for (int i = 0; i < numTasks; i++)
            {
                tasks[i] = Task.Run(() => new Job(state).DoTheJob());
            }
            for (int i = 0; i < numTasks; i++)
            {
                tasks[i].Wait();
            }
            Console.WriteLine("汇总 {0}", state.State);
        }
        public static void ThreadMonitor()
        {
            var obj = new object();
            Monitor.Enter(obj);
            try
            {

            }
            finally
            {
                Monitor.Exit(obj);
            }

            bool lockTaken = false;
            Monitor.TryEnter(obj, 500, ref lockTaken);
            if (lockTaken)
            {
                try
                {
                    
                }
                finally
                {
                    Monitor.Exit(obj);
                }

            }
            else
            {
                
            }
        }
    }
}
